package com.renrenapps.dopaminer.Action;


import com.renren.api.client.RenrenApiInvoker;
import com.renren.api.client.param.impl.AccessToken;
import com.renren.api.client.services.RenrenApiException;
import com.renren.api.client.services.StatusService;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.json.simple.JSONArray;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created with IntelliJ IDEA.
 * User: Wings
 * Date: 13-8-8
 * Time: 下午6:04
 * To change this template use File | Settings | File Templates.
 */
public class AuthAction {
    private String code;

    /**
     * 向指定URL发送POST方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是name1=value1&name2=value2的形式。
     * @return URL所代表远程资源的响应
     */
    private static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += System.lineSeparator() + line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public String execute() {
        String param = "grant_type=authorization_code" +
                "&client_id=f63486984e714372b1847542df5fc531" +
                "&redirect_uri=http%3A%2F%2Fapps.renren.com%2Fdopa_miner%2Fauth" +
                "&client_secret=24c24bf35f1f450e81124b1620cf9256" +
                "&code=" + this.getCode();
        String response = AuthAction.sendPost(GlobalConfig.renrenTokenURL, param);
        System.out.println(response);
        if (response == null || response == "") {
            return "input";
        }
        JSONObject jsonObject = null;
        String userid = null;
        String access_token = null;
        String refresh_token = null;
        try {
            jsonObject = new JSONObject(response);
            userid = jsonObject.getJSONObject("user").getString("id");
            access_token = jsonObject.getString("access_token");
            refresh_token = jsonObject.getString("refresh_token");
        } catch (JSONException e) {
            e.printStackTrace();
            return "input";
        }

        //写入文件
        if (!RecordStatus("E:\\", userid, access_token)) {
            return "input";
        }
        return "success";
    }

    public boolean RecordStatus(String filePath, String userid, String access_token) {
        File f = new File(filePath + "statuses_of_user_" + userid + ".xml");
        BufferedWriter output = null;
        if (!f.exists()) {
            try {
                f.createNewFile();
                output = new BufferedWriter(new FileWriter(f));
                output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                output.write(System.lineSeparator());
                output.write("<status_gets_response xmlns=\"http://api.renren.com/1.0/\" " +
                        "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
                        "xsi:schemaLocation=\"http://api.renren.com/1.0/ http://api.renren.com/1.0/renren.xsd\">");
                output.write(System.lineSeparator());
                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        String xml = "I make a difference because I am not empty inside ...";
        int currentPage = 1;
        while (!xml.equals("")) {
            xml = getStatuses(userid, currentPage, 50, access_token, 10);
            try {
                output.write(xml);
                output.write(System.lineSeparator());
                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            currentPage++;
        }
        try {
            output.write("</status_gets_response>");
            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public String getStatuses(String userid, int page, int count, String access_token, int maxTryTimes) {
        String jsonStatuses = null;
        int triedTimes = 0;
        while (jsonStatuses == null && triedTimes < maxTryTimes) {
            triedTimes++;
            jsonStatuses = getStatusesJsonString(userid, page, count, access_token);
        }
        if (jsonStatuses == null) {
            return "jsonStatuses is null.";
        }
        String xml = null;
        try {
            org.json.JSONArray json = new org.json.JSONArray(jsonStatuses);
            xml = XML.toString(json, "status");
        } catch (JSONException e) {
            e.printStackTrace();
            return "json parse error.";
        }
        if (xml == null) {
            return "xml is null.";
        }
        return xml;
    }

    private String getStatusesJsonString(String userid, int page, int count, String access_token) {
        AccessToken accessToken = new AccessToken(access_token);
        StatusService statusService = new StatusService(new RenrenApiInvoker());
        JSONArray statuses = null;
        try {
            statuses = statusService.getStatuses(Long.parseLong(userid), page, count, accessToken);
        } catch (RenrenApiException e) {
            if (e.getErrorCode() == 1) {
                return null;
            }
        }
        if (statuses == null) {
            return null;
        }
        String jsonString = statuses.toJSONString();
        return jsonString;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
